package com.tjkcht.midware.reader;

import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

/**
 * 补丁-->用于适配阅读器发送速率与中间件消耗速率不匹配时
 * 阅读器结果过滤器
 * 提供当前标签是否被过滤接口
 * */
public class ReaderResultFilter {
    private static Logger log = Logger.getLogger("ReaderResultFilter");
    private final Set<String> tags=new HashSet<>();
    private Long clearPeriod=500L;
    private String ip;

    public ReaderResultFilter(String ip){
        this.ip=ip;
        clearTags();
    }
    /**
     * 是否被过滤，被过滤则不应该再去处理此标签
     * */
    public boolean isFilter(String tagId){
        synchronized (tags){
            if(!tags.contains(tagId)){
                tags.add(tagId);
                return false;
            }
        }
        log.info("ip:"+ip+"阅读器，在"+clearPeriod+"ms内已有相同标签上报,epc:"+tagId);
        return true;
    }

    private void clearTags(){
        Timer timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                synchronized (tags){
                    log.info("ip:"+ip+"阅读器，清空过滤集");
                    tags.clear();
                }
            }
        },0,clearPeriod);
    }
}
